<template>
  <div class="pie-charts-container">
    <h4 class="title">{{ title }}</h4>
    <div class="pie-charts" ref="pieCharts"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'pie-charts',
  props: {
    title: {
      type: String,
      required: true,
    },
    list: {
      type: Array,
      required: true,
      default: () => [],
    },
  },
  methods: {
    initCharts() {
      this.charts = echarts.init(this.$refs.pieCharts)
      const list = this.list.map(item => ({
        name: item.channel,
        value: item.num,
      }))
      const options = {
        legend: {
          data: this.list.map(item => item.channel),
          orient: 'vertical',
          right: 4,
          top: 0,
          itemGap: 5,
        },
        series: [
          {
            type: 'pie',
            data: list,
            selectedMode: 'single', // 选中效果，选中区域会偏移原点一段距离
            radius: ['35%', '60%'],
            labelLine: {
              show: false, // 显示与隐藏，boolean
            },
            label: {
              show: false, // 是否展示标签
            },
          },
        ],
        tooltip: {
          show: true,
          trigger: 'item',
          // 返回值为提示的文本信息
          formatter: params => {
            // 当前item项的信息
            // console.log(params.data)
            const item = params.data
            return `${this.title}：${item.name}<br/>
                    ${this.title === '用户渠道' ? '用户数量' : '商品销量'}：${
              item.value
            }
            `
          },
        },
      }
      this.charts.setOption(options)
    },
  },
  mounted() {
    this.initCharts()

    this.$bus.$on('changeCollapse', () => {
      this.$nextTick(() => {
        // 调整图形的大小
        this.charts.resize()
      })
    })
  },
}
</script>

<style lang="scss" scoped>
.pie-charts-container {
  width: 100%;
  background-color: #f7f7f7;
  overflow: hidden;
  border-radius: 5px;
  margin-bottom: 15px;
  .pie-charts {
    width: 100%;
    height: 300px;
    margin: 0 auto;
  }
  .title {
    position: relative;
    margin-top: 10px;
    margin-left: 15px;
    padding-left: 10px;
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
      width: 2px;
      height: 14px;
      background-color: #1890ff;
    }
  }
}
</style>
